﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.IO;

namespace SinaAPIDocumentToRequestTool
{
    public class V1DocumentDataGetter : DocumentDataGetterBase
    {
        public override string HomeUrl
        {
            get { return "http://open.weibo.com/wiki/API%E6%96%87%E6%A1%A3"; }
        }



        public override string GetPath()
        {
            var catlog = _browser.Document
                .GetElementsByTagName("h2")
                .Cast<HtmlElement>()
                .Where(e => e.InnerText == "目录")

                .Single();
            return catlog
                .Parent
                .NextSibling
                .GetElementsByTagName("li")
                          .Cast<HtmlElement>()
                          .First()
                .FirstChild.Children[1]
                .InnerText.Trim();
        }

        public override string GetComment()
        {
            try
            {

                var sb = new StringBuilder("<para>");
                var aim = _browser.Document
                      .GetElementsByTagName("h2")
                      .Cast<HtmlElement>()
                      .Where(e => e.FirstChild != null)
                      .Where(e => string.Equals(e.FirstChild.InnerText.Trim(), GetPath(), StringComparison.CurrentCultureIgnoreCase))
                      .FirstOrDefault();
                sb.AppendLine(aim.NextSibling.InnerText);

                GetCommentField(sb, "URL");
                GetCommentField(sb, "支持格式");
                GetCommentField(sb, "HTTP请求方式");
                GetCommentField(sb, "是否需要登录");
                GetCommentField(sb, "请求数限制");

                GetCommentField(sb, "注意事项");
                sb.Replace("\r\n", "</para>\r\n<para>");
                sb.Append("</para>");
                return sb.ToString();
                
            }
            catch (Exception)
            {

                return "notext";
            }


        }

        private void GetCommentField(StringBuilder sb, string field)
        {
            try
            {


                var ele = GetFieldText(field);

                sb.AppendFormat(field).Append(":\r\n\t").Append(ele).AppendLine();
            }
            catch (Exception)
            {


            }
        }

        private string GetFieldText(string field)
        {
            var ele =
                _browser.Document
                .GetElementById(EncodeId(field))
                .NextSibling
                .NextSibling
                .InnerText
                .Replace("\r", " ")
                .Replace("\n", " ")
                .Trim();
            return ele;
        }


        public string EncodeId(string id)
        {
            return Uri.EscapeDataString(id).Replace("%", ".");
        }

        public override Dictionary<string,string[]> GetParamsAndParamsComment()
        {
            try
            {

                var field = "请求参数";
                var tbl =
                    _browser.Document
                    .GetElementById(EncodeId(field))
                    .NextSibling
                    .NextSibling;
                var headers = tbl.FirstChild.FirstChild.Children
                    .Cast<HtmlElement>()
                    .Select(x => x.InnerText.Trim() + ":")
                    .ToList();
                var trs = tbl.FirstChild.Children.Cast<HtmlElement>().Skip(1)
                    .ToList();

                return trs.Select(
                     tr
                     =>
                     {
                         var key = tr.FirstChild.InnerText.Trim();
                         var sb = new StringBuilder("<para>");
                         sb.AppendLine(key).AppendLine();
                         var sl =  tr.Children.Cast<HtmlElement>()
                             .Skip(1)

                             .Select
                             (
                                 (td, i) =>
                                 {
                                     sb.AppendLine(headers[i + 1]) 
                                         .Append("\t")
                                         .AppendLine(td.InnerText.Trim());
                                     return td.InnerText.Trim();
                                 }
                             )
                             .ToList();
                         sb.Append("</para>");
                         sb.Replace("\r\n","</para>\r\n<para>");
                         sl.Add(sb.ToString());
                         return new { key, List=sl };
                     }
                 )
                 .Where (x=>x.List.Count>=4)
                 .ToDictionary(x => x.key, x => x.List.ToArray());

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
            return new Dictionary<string, string[]>();
        }

        public override string GetWebMethod()
        {
            var sb = new StringBuilder();

            GetCommentField(sb, "HTTP请求方式");

            return sb.ToString();
        }

        public override string GetJsonResponse()
        {
            return GetFieldText("JSON示例");
        }
    }
}
